package com.codeworker.asyncrequestresenddemo.config;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Description: 线程池配置
 *
 * @author code-worker
 * @date 2021/10/13 15:16
 */
@Configuration
@EnableAsync
public class AsyncExecutor implements AsyncConfigurer {
    /**
     * 核心线程数
     */
    private static final int CORE_POOL_SIZE = 5;
    /**
     * 最大线程数
     */
    private static final int MAX_POOL_SIZE = 5;
    /**
     * 队列大小
     */
    private static final int QUEUE_CAPACITY = 50;
    /**
     * 线程池中的线程的名称前缀
     */
    private static final String THREAD_NAME = "MyExecutor-";
    /**
     * task: 线程池配置
     * @author code-worker
     * @date 2021/10/13 15:30
     * @return java.util.concurrent.Executor
     */
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //配置核心线程数
        executor.setCorePoolSize(CORE_POOL_SIZE);
        //配置最大线程数
        executor.setMaxPoolSize(MAX_POOL_SIZE);
        //配置队列大小
        executor.setQueueCapacity(QUEUE_CAPACITY);
        //配置线程池中的线程的名称前缀
        executor.setThreadNamePrefix(THREAD_NAME);
        //配置线程池拒绝策略，设置为CallerRunsPolicy，当线程和队列都满了，由发起线程的主线程自己执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
    /**
     * task: 池化异常信息提示
     * @author code-worker
     * @date 2021/10/13 15:39
     * @return org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler
     */
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (Throwable throwable, Method method, Object... objects) ->
        {
            System.out.println("throwable: " + throwable.getMessage());
            System.out.println("method: " + method.getName());
            System.out.println("objects: " + Arrays.toString(objects));
        };
    }

}

